#include "tinyxml2.h"
#include <iostream>
#include <vector>
#include <sstream>
#include <string>

using namespace tinyxml2;
using namespace std;

vector<int> splitChannelString(const string& str) {
    vector<int> channels;
    stringstream ss(str);
    string token;
    while (getline(ss, token, ',')) {
        channels.push_back(stoi(token));
    }
    return channels;
}

void printChannels(const vector<int>& channels) {
    for (size_t i = 0; i < channels.size(); ++i) {
        if (i > 0) cout << ", ";
        cout << channels[i];
    }
}

int main() {
    XMLDocument doc;
    if (doc.LoadFile("cross_effect.xml") != XML_SUCCESS) {
        cerr << "无法加载文件" << endl;
        return 1;
    }

    // 获取根节点
    XMLElement* root = doc.RootElement();
    if (!root) {
        cerr << "空XML文档" << endl;
        return 1;
    }

    // 解析delay部分
    if (XMLElement* delay = root->FirstChildElement("delay")) {
        // 读取duration属性
        int duration = 0;
        if (delay->QueryIntAttribute("duration", &duration) == XML_SUCCESS) {
            cout << "Delay Duration: " << duration << "ms" << endl;
        }

        // 读取通道数组
        if (XMLElement* array = delay->FirstChildElement("array")) {
            if (strcmp(array->Attribute("name"), "channels") == 0) {
                vector<int> channels;
                for (XMLElement* item = array->FirstChildElement("item");
                     item; 
                     item = item->NextSiblingElement("item")) {
                    if (const char* text = item->GetText()) {
                        channels.push_back(atoi(text));
                    }
                }
                cout << "Channels: ";
                printChannels(channels);
                cout << endl;
            }
        }
    }

    // 解析mixer部分
    if (XMLElement* mixer = root->FirstChildElement("mixer")) {
        int mixCount = 0;
        for (XMLElement* mix = mixer->FirstChildElement("mix");
             mix; 
             mix = mix->NextSiblingElement("mix")) {
            cout << "\nMix #" << ++mixCount << endl;

            // 解析source
            if (XMLElement* source = mix->FirstChildElement("source")) {
                vector<int> srcChannels = splitChannelString(source->Attribute("channel"));
                float gain = source->FloatAttribute("gain");
                
                cout << "  Source Channels: ";
                printChannels(srcChannels);
                cout << " | Gain: " << gain << endl;
            }

            // 解析target
            if (XMLElement* target = mix->FirstChildElement("target")) {
                vector<int> tgtChannels = splitChannelString(target->Attribute("channel"));
                float gain = target->FloatAttribute("gain");
                
                cout << "  Target Channels: ";
                printChannels(tgtChannels);
                cout << " | Gain: " << gain << endl;
            }
        }
    }

    return 0;
}
